import { NextRequest } from "next/server";
import { withMiddleware } from "@/lib/middleware/entry";
import { prisma } from "@/lib/prisma";
import { authenticateRequest } from "@/utils/auth";

async function handler(req: NextRequest) {
  const authResult = await authenticateRequest(req);
  if (!authResult.success || !authResult.user) {
    throw new Error(authResult.error || "认证失败");
  }
  const user = authResult.user;

  const { contentId } = await req.json();

  if (!contentId) {
    throw new Error("内容ID不能为空");
  }

  const existingFavorite = await prisma.favorite.findUnique({
    where: {
      userId_contentId: {
        userId: user.id,
        contentId: contentId,
      },
    },
  });

  if (existingFavorite) {
    await prisma.favorite.delete({
      where: {
        id: existingFavorite.id,
      },
    });

    await prisma.content.update({
      where: { id: contentId },
      data: {
        favoritesCount: {
          decrement: 1,
        },
      },
    });

    return { message: "取消收藏成功" };
  } else {
    await prisma.favorite.create({
      data: {
        userId: user.id,
        contentId: contentId,
      },
    });

    await prisma.content.update({
      where: { id: contentId },
      data: {
        favoritesCount: {
          increment: 1,
        },
      },
    });

    return { message: "收藏成功" };
  }
}

export const POST = withMiddleware(handler);